package com.cn.ZhiKeDianShang.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.adapter.TasksBeanAdapter;
import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.response.hesuanBean;
import com.cn.ZhiKeDianShang.model.response.oderLiist;
import com.cn.ZhiKeDianShang.presenter.MineFragmentPresenter;
import com.cn.ZhiKeDianShang.presenter.view.MineFragmentView;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.TimeUtil;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 搜索列表
 * Created by chengaofu on 2017/6/21.
 */

public class SerchlistActivity extends BaseActivity<MineFragmentView, MineFragmentPresenter> implements MineFragmentView {


    @BindView(R.id.rc_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.fragment_list_swip)
    SwipeRefreshLayout fragmentListSwip;
    @BindView(R.id.rl_image_text)
    RelativeLayout rlImageText;
    Unbinder unbinder;
    @BindView(R.id.tv_benjin)
    TextView tvBenjin;
    @BindView(R.id.tv_zhifu)
    TextView tvZhifu;
    @BindView(R.id.tv_hesuan)
    TextView tvHesuan;
    @BindView(R.id.ll_empty)
    RelativeLayout ll_empty;


    private ProgressDialogFragment mProgressDialog;

    int currentPage = 1;
    int pageNumber = 10;
    //上拉加载  还有没有数据
    boolean isHaveDate = true;

    private List<oderLiist.TasksBean> mList = new ArrayList<>();
    private TasksBeanAdapter mAdapter;
    int type;   //0 搜索界面   1 筛选  2 历史搜索
    String tasknum = "";   //任务编号

    String teamid = "";   //筛选 团队id
    String status = "";   ///筛选 状态值
    String start = "";   ///筛选 开始时间
    String end = "";   //筛选 结束时间

    @Override
    protected void initViewsAndEvents() {
        type = getIntent().getIntExtra("type", 0);
        tasknum = getIntent().getStringExtra("tasknum");

        teamid = getIntent().getStringExtra("teamid");
        status = getIntent().getStringExtra("status");
        start = getIntent().getStringExtra("start");
        end = getIntent().getStringExtra("end");

        fragmentListSwip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getData();
            }
        });

        initRecyclerView();
        getData();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //得到当前显示的最后一个item的view
                View lastChildView = recyclerView.getLayoutManager().getChildAt(recyclerView.getLayoutManager().getChildCount() - 1);
                if (lastChildView != null) {
                    //得到lastChildView的bottom坐标值
                    int lastChildBottom = lastChildView.getBottom();
                    //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
                    int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
                    //通过这个lastChildView得到这个view当前的position值
                    int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);

                    //判断lastChildView的bottom值跟recyclerBottom是否相等
                    //判断lastPosition是不是最后一个position
                    if (lastChildBottom == recyclerBottom && lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                        ToastUtil.showShort("滑动到底部了");
                        if (isHaveDate) {
                            currentPage++;
                            getData();
                        }
                    }
                }
            }
        });

    }

    private void initRecyclerView() {
        mAdapter = new TasksBeanAdapter(SerchlistActivity.this, R.layout.item_video_like, mList, new TasksBeanAdapter.onItemClick() {
            @Override
            public void onItemClick(int position) {
                ToastUtil.showShort("点击事件" + position);
                startActivity(new Intent(SerchlistActivity.this, OrderDetailActivity.class).putExtra("taskid", mList.get(position).getId() + ""));
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(SerchlistActivity.this));
        mRecyclerView.setAdapter(mAdapter);
    }


    /**
     * @param
     */
    private void getData() {
        String url = "";
        Map<String, String> params = new HashMap<>();
        switch (type) {
            case 0:
                params.put("tasknum", tasknum);
                url = AppConfig.ORDER_SERCH;
                break;
            case 1:
                if (!TextUtils.isEmpty(teamid)) {
                    params.put("teamid", teamid);
                }
                if (!TextUtils.isEmpty(status)) {
                    params.put("status", status);
                }
                if (!TextUtils.isEmpty(start)) {
                    params.put("start", TimeUtil.convertTimeToLong10(start, "yyyy-MM-dd HH:mm") / 1000 + "");
                }
                if (!TextUtils.isEmpty(end)) {
                    params.put("end", TimeUtil.convertTimeToLong10(end, "yyyy-MM-dd HH:mm") / 1000 + "");
                }
                url = AppConfig.ORDER_SELECT;
                break;
            case 2:
                break;
        }
        params.put("page", currentPage + "");
        params.put("pagesize", pageNumber + "");
        HttpUtils.post().url(url)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<oderLiist>(oderLiist.class) {
                    @Override
                    public void onResponse(ObjectResult<oderLiist> result) {
                        if (Result.checkSuccess(SerchlistActivity.this, result)) {
                            oderLiist data = result.getData();
                            if (currentPage == 1) {
                                mAdapter.setData(data.getTasks());
                                if (data.getTasks().size() == 0) {
                                    ll_empty.setVisibility(View.VISIBLE);
                                } else {
                                    ll_empty.setVisibility(View.GONE);
                                }
                            } else {
                                ll_empty.setVisibility(View.GONE);
                                mAdapter.addAll(data.getTasks());
                            }
                            //所返回的数据个数 没有pageNumber 个的  说明已经没有数据了
                            if (data.getTasks().size() != pageNumber) {
                                isHaveDate = false;
                            } else {
                                isHaveDate = true;
                            }
                            mList = mAdapter.getAll();
                            mAdapter.notifyDataSetChanged();
                        }
                        if (fragmentListSwip != null) {
                            fragmentListSwip.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (fragmentListSwip != null) {
                            fragmentListSwip.setRefreshing(false);
                        }
                    }
                });

    }

    /**
     * @param
     */
    private void checkMoney() {
        Map<String, String> params = new HashMap<>();
        if (type==0){
            if (!TextUtils.isEmpty(tasknum)) {
                params.put("tasknum", tasknum);
            }
        }else {
            if (!TextUtils.isEmpty(teamid)) {
                params.put("teamid", teamid);
            }
            if (!TextUtils.isEmpty(status)) {
                params.put("status", status);
            }
            if (!TextUtils.isEmpty(start)) {
                params.put("start", TimeUtil.convertTimeToLong10(start, "yyyy-MM-dd HH:mm") / 1000 + "");
            }
            if (!TextUtils.isEmpty(end)) {
                params.put("end", TimeUtil.convertTimeToLong10(end, "yyyy-MM-dd HH:mm") / 1000 + "");
            }
        }
        HttpUtils.post().url(AppConfig.ORDER_ACCOUNTING)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<hesuanBean>(hesuanBean.class) {
                    @Override
                    public void onResponse(ObjectResult<hesuanBean> result) {
                        if (Result.checkSuccess(SerchlistActivity.this, result)) {
                            hesuanBean data = result.getData();
                            tvZhifu.setText("实际总支付：" + data.getPay());
                            tvBenjin.setText("任务总本金：" + data.getZje());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });

    }


    @Override

    public void onResume() {
        super.onResume();

    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.serch_ordlist_layout;
    }

    @Override
    protected MineFragmentPresenter createPresenter() {
        return null;
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.serch_ordlist_layout;
    }


    @Override
    public void requestFailed(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.setting_back, R.id.tv_hesuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.tv_hesuan:
                checkMoney();
                break;

        }
    }

}